//
//  MCChooseMultiplePicturesView.swift
//  CityPlatform
//
//  Created by MC on 2018/12/19.
//  Copyright © 2018 MC. All rights reserved.
//

import UIKit
import SnapKit


/**
 说明
 1. 如何获取选中的图片？  属性获取imageArray
 2.
 */
public class MCPickerImageView: UIView {
    
    /// 是否支持拍照获取图片裁切功能
    public var isNeedEditImage = false
    public var bigImageCount = 6
    
    // [UIImage]()
    public var imageArray: [UIImage] = [] {
        didSet {
            self.colleciontView.reloadData()
        }
    }
    
    
    public var itemSize: CGSize = CGSize(width: 90, height: 90) {
        didSet {
            layout.itemSize = itemSize
        }
    }
    
    public var spacing: CGFloat = 5 {
        didSet {
            layout.minimumLineSpacing = spacing
            layout.minimumInteritemSpacing = spacing
        }
    }
    
    public var insets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) {
        didSet {
            layout.sectionInset = insets
        }
    }
    
    /// 默认图片（添加图片）
    public var defaultImage: UIImage?

    public var cancelImage: UIImage?

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.white
        
        self.addSubview(promptLabel)
        promptLabel.snp.remakeConstraints { (make) ->Void in
            make.top.equalTo(self)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(30)
        }
        
        self.addSubview(colleciontView)
        colleciontView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(promptLabel.snp.bottom).offset(0)
            make.bottom.equalTo(self)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    public lazy var promptLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.mc14
        label.text = "选择图片"
        label.textColor = UIColor.mc_lightGray
        return label
    }()
    

    
    
    @objc func deleteEvent(sender:UIButton) {
        let tag = sender.tag - 1000
        imageArray.remove(at: tag)
        colleciontView.reloadData()
    }
    
    func chooseImage() {
        
        let vc = UIViewController.current()
        UIAlertController.mc_chooseImage(on: vc) { (title) in
            
            if title == "拍照" {
                MCPickerImageHelper.mc_openCamera(vc, completeHandler: { (image) in
                    self.imageArray.append(image)
                    self.colleciontView.reloadData()
                })
            } else if title == "相册" {
                
                /// 重新计算当前最大值
                let nowMaxCount = self.bigImageCount - self.imageArray.count
                
                MCPickerImageHelper.mc_openCustomLibrary(target: vc, mediaType: .image, maxSelectCount: nowMaxCount) { (assets) in
                    
                    for asset in assets {
                        self.imageArray.append(asset.toImage())
                    }
                    self.colleciontView.reloadData()
                }
            }
        }
    }
    
    
    
    
    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout.init()
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize.init(width: 90, height: 90)
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 0, right: 5)
        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5
        return layout
    }()
    
    
    private lazy var colleciontView: UICollectionView = {
        
        //  68  97
        let collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        
        collectionView.register(MCPickerImageCell.self, forCellWithReuseIdentifier: "customCell")

        
        collectionView.delegate = self
        collectionView.dataSource = self
        
        return collectionView
    }()
}

extension UIViewController {
    
    /** 获取当前控制器 */
    static func current() -> UIViewController {
        let vc = UIApplication.shared.keyWindow?.rootViewController
        return UIViewController.findBest(vc: vc!)
    }
    
    private static func findBest(vc: UIViewController) -> UIViewController {
        if vc.presentedViewController != nil {
            return UIViewController.findBest(vc: vc.presentedViewController!)
        } else if vc.isKind(of: UISplitViewController.self) {
            let svc = vc as! UISplitViewController
            if svc.viewControllers.count > 0 {
                return UIViewController.findBest(vc: svc.viewControllers.last!)
            } else {
                return vc
            }
        } else if vc.isKind(of: UINavigationController.self) {
            let svc = vc as! UINavigationController
            if svc.viewControllers.count > 0 {
                return UIViewController.findBest(vc: svc.topViewController!)
            } else {
                return vc
            }
        } else if vc.isKind(of: UITabBarController.self) {
            let svc = vc as! UITabBarController
            if (svc.viewControllers?.count ?? 0) > 0 {
                return UIViewController.findBest(vc: svc.selectedViewController!)
            } else {
                return vc
            }
        } else {
            return vc
        }
    }
}

extension MCPickerImageView : UICollectionViewDelegate,UICollectionViewDataSource {
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if imageArray.count >= bigImageCount {
            return imageArray.count
        } else {
            return imageArray.count + 1
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
         
        if (imageArray.count < bigImageCount) && (imageArray.count == indexPath.row) {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
            
            for view in cell.contentView.subviews {
                view.removeFromSuperview()
            }
            
            let imageView = UIImageView()
            
            
            if defaultImage != nil {
                imageView.image = defaultImage
            } else {
                let image = Bundle.mc_loadImage("image_add", from: "MCPhotoLibraryBundle", in: "MCComponentFunction")
                imageView.image = image
            }
            
            imageView.layer.borderColor = UIColor.mc_line.cgColor
            imageView.layer.borderWidth = 1
            cell.contentView.addSubview(imageView)
            imageView.snp.remakeConstraints { (make) ->Void in
                make.edges.equalTo(cell.contentView)
            }
            return cell
        } else {
            
            let reuseIdentifier = "customCell"
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MCPickerImageCell

            for view in cell.contentView.subviews {
                view.removeFromSuperview()
            }
            cell.showImageView.image = self.imageArray[indexPath.row]

            cell.row = indexPath.row
            cell.delegate = self
            cell.cancelImage = cancelImage
            return cell
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if imageArray.count == 0 {
            self.chooseImage()
            return
        }
        
        if imageArray.count < bigImageCount && indexPath.row == imageArray.count {
            self.chooseImage()
        } else {
            //                print("点击了图片")
        }
    }
}

extension MCPickerImageView : MCPickerImageCellDelegate {
    
    public func pickerImageCell(_ view: MCPickerImageCell, deleteImageAtRow row: Int) {
        imageArray.remove(at: row)
        self.colleciontView.reloadData()
    }
}
